﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace VBAConvertor.Parsers
{
    public class SubParser : ILineParser
    {
        private readonly bool _AutoAddDocument;
        public SubParser(bool autoAddDocument)
        {
            _AutoAddDocument = autoAddDocument;
        }

        private static readonly Regex SubPattern =
            new Regex(
                @"^(((Public)|(Private)) )?Sub (?<name>[a-zA-Z_][\w_]*)\((?<params>[^\(\)]*)\)$",
                RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.Singleline);

        public string Parse(Stack<ParseStatus> statuses, string lineContent, LinesReader reader, out bool success,
                            ref bool lineClosed)
        {
            var match = SubPattern.Match(lineContent);
            success = match.Success;
            if (!success)
            {
                return lineContent;
            }
            if (statuses.Peek().CurrentState != State.ClassDef || lineClosed)
            {
                throw new Exception();
            }
            lineClosed = true;
            statuses.Push(new ParseStatus {CurrentState = State.SubDef});
            var vars = ParserHelper.GetVarDefs(match.Groups["params"].Value, ",");
            string appDef = null;
            if (_AutoAddDocument)
            {
                if (!string.IsNullOrEmpty(vars))
                {
                    vars = ", " + vars;
                }
                vars = "Document " + ParserHelper.DocumentParamName + vars;
                appDef = string.Format("var {0} = {1}.Application;", ParserHelper.AppVariableName, ParserHelper.DocumentParamName);
            }
            return string.Format("void {0}({1}){{", match.Groups["name"].Value, vars) + appDef;
        }
    }
}
